package factory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import bean.*;

/**
 * class TemplateFacotry is the factory class, which adopts factory method design pattern
 * And this class itself has been applied for <font color="red">Singleton design pattern</font>
 * @author xijiang
 */
public class TemplateFactory {

	private final static String TEMPLATE_PREFIX = "bean.";
	private final static TemplateFactory factory = new TemplateFactory();
	
	private TemplateFactory() {
		
	}
	
	public static TemplateFactory getInstance() {
		return factory;
	}
	
	/**
	 * According to the passed in parameters, factory create and return the Template
	 * @param type 	the type of template which has been defined in BAI.xml indicated by "type"
	 * @param attributeNames all the attributes contained in the BAI file
	 * @param content the raw content of the BAI file
	 * @return
	 */
	public ITemplate createTemplate(String type, ArrayList<String> attributeNames, String content) {
		
		ITemplate template = null;
		try {
			template = (ITemplate) Class.forName(TEMPLATE_PREFIX+type).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		//set template's type
		if(template!=null) {
			template.setType(type);
		}
		
		/*
		 * register all attributes
		 */
		Iterator<String> iter = attributeNames.iterator();
		while(iter.hasNext()) {
			template.registerAttribute(iter.next());
		}
		
		//set the content of the template
		template.setContent(content);
		
//		System.out.println("A---TemplateFactory: -----------------------");
//		System.out.println("type: " + template.getType() );
//		System.out.println("content: " + template.getContent());
//		Set<String> set = template.getAttrNameSet();
//		for(String s: set) {
//			System.out.print(s+"\t");
//		}
//		System.out.println();
//		System.out.println("B---TemplateFactory: -----------------------");
//		System.out.println();
		
		return template;
	}

}
